package com.drerp.autenticacao;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.drerp.RH.Usuario;
import com.drerp.util.Constantes;

public class FiltroAutenticacao implements Filter {
	private FilterConfig filterConfig;

	@Override
	public void destroy() { }

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpReq = ((HttpServletRequest) request);
		HttpServletResponse httpResp = ((HttpServletResponse) response);
		
		String path = httpReq.getRequestURI();
		
		Usuario usuario = (Usuario) httpReq.getSession().getAttribute(Constantes.USER_SESSION_KEY);

		if (usuario == null && !path.endsWith(Constantes.LOGIN_URL)) {
			httpReq.getSession().setAttribute(Constantes.URL_DEST_SESSION_KEY, path);

			httpResp.sendRedirect(Constantes.LOGIN_URL);
			chain.doFilter(request, response);
			return;
			
		} else if (usuario != null) {
			chain.doFilter(request, response);
			return;
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

}
